package kr.saeildamil.androidstudy_second.draw;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {
	ArrayList<Ball> arBall;
	final static int DELAY = 50;
	
	public MyView(Context context) {
		super(context);
		arBall = new ArrayList<Ball>();
		mHandler.sendEmptyMessageDelayed(0, DELAY);
	}	

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN){
			Ball newBall = new Ball((int)event.getX(), (int)event.getY());
			arBall.add(newBall);
			invalidate();	//onDraw()를 호출해서 추가된 볼을 그려주도록 함.
			return true;
		}
		return false;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		for (int i=0; i< arBall.size(); i++){
			arBall.get(i).Draw(canvas);
		}
	}


	Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			Ball B;
			for(int i=0; i<arBall.size(); i++){
				B = arBall.get(i);
				B.Move(getWidth(), getHeight());//볼이 이동
				if (B.count>4){
					arBall.remove(i);
					i--;
				}
			}
			invalidate();
			mHandler.sendEmptyMessageDelayed(0, DELAY);
		}
	};
}
